﻿using System;
using System.Collections.Generic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Cache.Generic;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Game.Context;
using ZyGames.Framework.Game.Contract;
using ZyGames.Framework.Game.Contract.Action;
using ZyGames.Framework.Game.Lang;
using ZyGames.Framework.Game.Service;
using System.Linq;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.DZPocker.Script;
using ZyGames.Framework.Net;
using ZyGames.DZPocker.Tools;
using System.Threading;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 申请取消保险
	/// </summary>
	public class Action30023 : BaseAction
	{
		private int tableId;
		private int userId;
		private int posId;

		private TableData _currentTable;
		private GameUser _currentGameUser;

		private bool _result = false;
		private string _log = "";

		public Action30023(HttpGet actionGetter)
			: base((short)ActionType.DZApplyCancelInsurance, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetInt("TableId", ref tableId) &&
				httpGet.GetInt("UserId", ref userId))
			{
				return true;
			}
			return false;
		}

		public override bool TakeAction()
		{
			_currentTable = GameRoom.Current.GetTableData(tableId);
			if (_currentTable == null)
			{
				Tool.WriteWarmingLine("消息30023获得房间不存在");
				return false;
			}
			_currentGameUser = GameTable.Current.GetUser(userId);
			if (_currentGameUser == null)
			{
				Tool.WriteWarmingLine("消息30023玩家不存在");
				return false;
			}
			if (_currentTable.State != TableState.Insurance)
			{
				Tool.WriteWarmingLine("消息30023 当前房间不是保险状态");
				return false;
			}
			if (_currentTable.CurrentRoundBuyInsuranceUsersID.ContainsKey(userId))
			{
				_currentTable.CurrentRoundBuyInsuranceUsersID[userId] = true;
				for(int i = 0; i < _currentTable.InsurancePool.Count; i++)
				{
					var pool = _currentTable.InsurancePool[i];
					if(pool.MaxUserId == userId)
					{
						if (!pool.CurrentRoundIsOperated)
							pool.CurrentRoundIsOperated = true;
					}
				}
			}
			else
			{
				Tools.Tool.WriteErrorLine("该保险人没有操作保险的权限");
				return false;
			}

			var parameters = new Parameters();
			parameters["TableID"] = tableId;
			parameters["UserID"] = userId;
			GameTable.Current.SyncNotifyAction((int)ActionType.DZBrocastCancelInsurance, _currentTable, parameters, t =>
			{
				Console.WriteLine("Action 30024 广播玩家取消购买保险");
			});

			
			_result = true;
			return true;
		}

		public void ThreadFunc()
		{
			Tool.WriteErrorLine("回合结束操作，延时0.5s");
			System.Threading.Thread.Sleep(500);

			GameTable.Current.RoundInsuranceOperate(_currentTable);
		}

		public override void BuildPacket()
		{
			this.PushIntoStack(this.tableId);
			this.PushIntoStack(this._result);
			this.PushIntoStack(this._log);
			//开启新的线程来避免阻塞
			Thread t1 = new Thread(new ThreadStart(ThreadFunc));
			t1.IsBackground = true;
			t1.Start();
		}
	}
}
